<template>
  <div class="main sku-warning">
    <el-card class="box-card">
      <el-form :model="formData" :rules="rulesBase" size="medium" ref="formBase" label-width="160px">
        <el-form-item label="设置局部商品库存告警:" prop="freightTemplateId">
          <el-button  type="primary" @click="handleAddGoods">添加商品</el-button>
        </el-form-item>
        <el-form-item>
           <el-table :data="goodsList" border highlight-current-row>
            <el-table-column type="index" label="序号" width="80" align="center"></el-table-column>
            <el-table-column prop="goodsName" label="商品名称"  align="center"></el-table-column>
            <el-table-column prop="goodsCode" label="商品编码"  align="center"></el-table-column>
            <el-table-column prop="num" label="商品库存"  align="center"></el-table-column>
            <el-table-column label="操作" align="center" >
              <template slot-scope="scope">
                <el-button type="primary" size="mini" @click="handleSetSku(scope.row)">设置</el-button>
                <el-button type="danger" size="mini" @click="removeSkuGoods(scope.row)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-form-item>
        <!-- <el-form-item label="告警通知人:" prop="name">
          <el-input v-model="formData.name" placeholder='请输入手机号码，最多5人，以","间隔'/>
        </el-form-item> -->
        <el-form-item>
         <el-button type="primary" size="mini" @click="handleSave">确定</el-button>
        </el-form-item>
      </el-form>
    </el-card>
    <el-dialog title="设置" :visible.sync="showSetSku" width="100%" custom-class="dialog-sku">
      <el-table :data="goodsSkuList" border highlight-current-row>
        <el-table-column prop="skuCode" label="SKU编码"  align="center"></el-table-column>
        <el-table-column prop="attrValue1" label="属性1"  align="center" width="80"></el-table-column>
        <el-table-column prop="attrValue2" label="属性2"  align="center" width="80"></el-table-column>
        <el-table-column prop="totalSkuNumber" label="库存数"  align="center" width="80"></el-table-column>
        <el-table-column prop="warnThreshold" label="库存告警值"  align="center">
          <template slot-scope="scope">
            <el-form
              :ref="`form${scope.row.id}`"
              :model="scope.row"
              label-position="left"
            >
              <el-form-item label="" prop="warnThreshold" :show-message="false" required>
                <el-input v-model="scope.row.warnThreshold" placeholder="大于等于0的正整数" maxlength="8" @input="scope.row.warnThreshold=$event.replace(/[^\d]/g,'')"/>
              </el-form-item>
            </el-form>
          </template>
        </el-table-column>
        <el-table-column label="操作"  align="center" width="200">
          <template slot-scope="scope">
            <el-button type="danger" size="mini" @click="removeSku(scope.row)">删除</el-button>
            <el-button type="primary" size="mini" v-if="scope.$index === 0" @click="batchSetSku(scope.row)">批量设置</el-button>
          </template>
        </el-table-column>
      </el-table>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="saveSku">确 定</el-button>
        <el-button @click="showSetSku=false">取 消</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
export default {
  data() {
    return {
      formData: {},
      rulesBase: {},
      goodsList: [],
      showSetSku: false,
      goodsSkuList: [],
      goodsId: '',
      goodsSkuListAll: [],
      arrResult: []
    }
  },
  created () {
    this.getGoods()
  },
  methods: {
    // 获取已经设置过预警的商品
    getSku (goodsId) {
      return new Promise((resolve, reject) => {
        this.request({
          url: '/bsnl-product/goodssku/listWarnGoodsSku',
          method: 'get',
          params: {
            goodsId: goodsId
          }
        }).then((res) => {
          if (res.code === 200 || res.status === 200) {
            resolve(res.data2)
          }
        }).catch(err => {
          console.log(err)
        })
      })
    },
    // 获取已经设置过预警的商品
    getGoods () {
      this.request({
        url: '/bsnl-product/goods/listWarnGoods',
        method: 'get'
      }).then((res) => {
        if (res.code === 200 || res.status === 200) {
          this.goodsList = res.data2
        }
      }).catch(err => {
        console.log(err)
      })
    },
    // 批量设置库存警告
    batchSetSku (row) {
      this.goodsSkuList.forEach((item) => {
        this.$set(item, 'warnThreshold', row.warnThreshold)
      })
    },
    // 保存库存警告设置
    async saveSku () {
      let arrMap = this.goodsSkuList.map((item) => {
        if (this.$refs[`form${item.id}`]) {
          return this.$refs[`form${item.id}`].validate().catch(err=>{ console.log(err) })
        }
      })
      let resultArr = await Promise.all(arrMap)
      if (resultArr.indexOf(undefined) === -1) {
        let warnThresholds = []
        this.goodsSkuList.forEach((item) => {
          warnThresholds.push({
            skuCode: item.skuCode,
            warnThreshold: item.warnThreshold
          })
        })
        this.goodsSkuListAll.push({
          goodsId: this.goodsId,
          warnThresholds: warnThresholds
        })
        this.showSetSku = false
      } else {
        this.$message.error('库存告警值必填')
      }
    },
    async getSkuAttr (row) {
      let arr = await this.getSku(row.goodsId)
      if (arr.length === 0) {
        this.request({
          url: '/bsnl-product/goods/details',
          method: 'get',
          params: {
            id: row.id,
            userId: this.$store.getters.userId
          }
        }).then((res) => {
          if (res.code === 200 || res.status === 200) {
            this.goodsSkuList = res.data.goodsAttr
            this.goodsId = res.data.goods.goodsId
          }
        }).catch(err => {
          console.log(err)
        })
      } else {
        this.goodsSkuList = arr
        this.goodsId = arr[0].goodsId
      }
    },
    // 库存警告商品设置
    handleSetSku(row) {
      this.showSetSku = true
      this.getSkuAttr(row)
    },
    // 删除库存警告设置
    removeSku (item) {
      this.$confirm(`确定要删除该属性吗?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.request({
          url: '/bsnl-product/goodssku/removeWarnGoodsSkuBySkuCode',
          method: 'get',
          params: {
            skuCode: item.skuCode
          }
        }).then((res) => {
          if (res.code === 200 || res.status === 200) {
            this.$message.success('删除成功')
          }
        }).catch(err => {
          console.log(err)
        })
        this.goodsSkuList.splice(this.goodsSkuList.indexOf(item), 1)
      }).catch(err => {
        console.log(err);
      });
    },
    // 保存库存警告设置
    handleSave() {
      this.$refs['formBase'].validate(val => {
        if (val) {
          if (this.arrResult.length > 0) {
            this.arrResult.forEach((item) => {
              this.request({
                url: '/bsnl-product/goods/removeWarnGoods',
                method: 'get',
                params: {
                  goodsId: item.goodsId
                }
              }).catch(err => {
                console.log(err)
              })
            })
          }
          if (this.goodsSkuListAll.length === 0) {
            return;
          }
          this.request({
            url: '/bsnl-product/goodssku/setWarnThreshold',
            method: 'post',
            data: this.goodsSkuListAll
          }).then((res) => {
            if (res.code === 200 || res.status === 200) {
              this.$message.success('设置成功')
            }
          }).catch(err => {
            console.log(err)
          })
        }
      })
    },
    // 添加库存商品
    handleAddGoods() {
      let beforeList = this.goodsList
      let selected = this.goodsList.map(item => {
        return {
          id: item.id,
          goodsId: item.goodsId,
          serialNo: item.goodsCode,
          name: item.goodsName,
          stockQuantity: item.num
        }
      });
      this.goodsChoose({}, selected).then(val => {
        this.goodsList = this.goodsList.filter(item=>item.type===2).concat(val.map(item => {
          return {
            id: item.id,
            goodsId: item.goodsId,
            goodsCode: item.serialNo,
            goodsName: item.name,
            num: item.stockQuantity,
            type: 1,
            from_type: 1
          }
        }))
        let obj = {} //临时对象
        let arrResult = []
        this.goodsList.forEach(function (item, index) {
          obj[item.id] = true
        })
        beforeList.forEach(function (item, index) {
          if (!obj[item.id]) {
            arrResult.push(item)
          }
        })
        this.arrResult = arrResult
      });
    },
    // 删除库存商品
    removeSkuGoods(item) {
      this.$confirm(`确定要删除 ${item.goodsName} 吗?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.request({
          url: '/bsnl-product/goods/removeWarnGoods',
          method: 'get',
          params: {
            goodsId: item.goodsId
          }
        }).then((res) => {
          if (res.code === 200 || res.status === 200) {
            this.$message.success('删除成功')
          }
        }).catch(err => {
          console.log(err)
        })
        this.goodsList.splice(this.goodsList.indexOf(item), 1)
      }).catch(err => {
        console.log(err);
      });
    }
  }
}
</script>
<style lang="scss" scoped>
.sku-warning {
  /deep/ .el-dialog {
    max-width: 1000px;
  }
}
.dialog-sku {
  .el-form-item {
    margin-bottom: 0;
  }
}
</style>
